#!/bin/bash
set -e

CUR_DIR=$(dirname $(readlink -f ${BASH_SOURCE[0]}))
source ${CUR_DIR}/common.sh

WORKING_DIR=${PRJ_ROOT}
XMAKE_DIR=${PRJ_ROOT}/xmake_globaldir
if [[ -z "${XMAKE_GENERATOR_COMPDB_LSP}" ]]; then
    XMAKE_GENERATOR_COMPDB_LSP="clangd"
fi

function run_in_docker()
{
    docker run --rm \
    -v ${PRJ_ROOT}:${WORKING_DIR} \
    -e XMAKE_STATS=n \
    -e XMAKE_GLOBALDIR=${XMAKE_DIR} \
    -e XMAKE_GENERATOR_COMPDB_LSP=${XMAKE_GENERATOR_COMPDB_LSP} \
    -w ${WORKING_DIR} \
    --entrypoint "" \
    ${BUILD_IMAGE} bash "$@"
}

function run_shell_in_docker()
{
    docker run --rm -it \
    -v ${PRJ_ROOT}:${WORKING_DIR} \
    -e XMAKE_STATS=n \
    -e XMAKE_GLOBALDIR=${XMAKE_DIR} \
    -e XMAKE_GENERATOR_COMPDB_LSP=${XMAKE_GENERATOR_COMPDB_LSP} \
    -w ${WORKING_DIR} \
    ${BUILD_IMAGE}
}

function do_build()
{
    run_in_docker ${WORKING_DIR}/infra/bin/build-binary $jobs ${WORKING_DIR}/output
}

function do_config()
{
    run_in_docker ${WORKING_DIR}/infra/bin/build-config ${mode}
}

function do_format()
{
    run_in_docker ${WORKING_DIR}/infra/bin/check-clang-format
}

function do_clean()
{
    run_in_docker ${WORKING_DIR}/infra/bin/build-clean
}

command=${1:-build}
mode=${2:-debug}
jobs=1


if [[ ! "${command}" =~ ^(config|build|format|clean|attach)$ ]]; then
    echo "Invalid command: ${command}"
    exit 1
fi

if [[ ! "${mode}" =~ ^(debug|releasedbg|release|releaseasan)$ ]]; then
    echo "Invalid mode: ${mode}"
    exit 1
fi

if [[ ${command} == "config" ]]; then
    do_config
elif [[ ${command} == "build" ]]; then
    do_build
elif [[ ${command} == "format" ]]; then
    do_format
elif [[ ${command} == "clean" ]]; then
    do_clean
elif [[ ${command} == "attach" ]]; then
    run_shell_in_docker
fi